<template>
  <div>
    <el-dialog
      width="600px"
      :title="type == 'add' ? $t('新增') : $t('修改')"
      destroy-on-close
      append-to-body
      :visible.sync="show"
      :before-close="cancel"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" controls-position="right" :min="0" :precision="0" />
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">
            全选/全不选
          </el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">
            父子联动
          </el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item :label="$t('备注')">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="form.roleIdDistr"
          v-hasPermi="['distribution:roleDistr:editD']"
          type="primary"
          @click="submitForm('edit')"
        >
          确定修改
        </el-button>
        <el-button type="primary" v-hasPermi="['distribution:roleDistr:insertD']" v-else @click="submitForm('add')">
          确定新增
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { roleDistrMenuTree } from '@/api/platform/role'
import { editD, insertD } from '@/api/platform/supplierManage'

import { treeselect as menuTreeselect } from '@/api/system/menu'

export default {
  props: {
    /**
     * formData
     */
    formData: {
      type: Object,
      default: () => ({}),
    },
    /**
     * type
     */
    type: {
      type: String,
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },

  data() {
    return {
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 菜单列表
      menuOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      // 表单参数
      form: {
        roleName: '',
        roleSort: '',
      },
      // 表单校验
      rules: {
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        roleSort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }],
      },
    }
  },
  computed: {},
  watch: {
    show: function (newValue) {
      if (newValue) {
        Object.keys(this.form).forEach((key) => (this.form[key] = ''))
        this.getList()
      }
    },
  },
  methods: {
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true : false
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true : false
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : [])
      }
    },
    /** 提交按钮 */
    submitForm: function (type) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (type == 'edit') {
            this.form.menuIds = this.getMenuAllCheckedKeys()
            editD(this.form).then((res) => {
              this.$modal.msgSuccess(res.msg)
              this.cancel()
            })
          }
          if (type == 'add') {
            this.form.menuIds = this.getMenuAllCheckedKeys()
            insertD(this.form).then((res) => {
              this.$modal.msgSuccess(res.msg)
              this.cancel()
            })
          }
        }
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    async getList() {
      await this.getMenuTreeselect()
      const roleId = this.formData.roleIdDistr
      if (this.type == 'edit') {
        roleDistrMenuTree(roleId).then((response) => {
          this.form = { ...response.data.roleDistr }
          this.open = true
          this.$nextTick(() => {
            let checkedKeys = response.data.checkedKeys
            checkedKeys.forEach((v) => {
              this.$nextTick(() => {
                this.$refs.menu.setChecked(v, true, false)
              })
            })
          })
          this.title = '修改角色'
        })
      }
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      return menuTreeselect().then((response) => {
        this.menuOptions = response.data
      })
    },
    handleSubmit() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
        }
      })
    },
    cancel() {
      this.$emit('update:show', false)
      this.$emit('getList')
    },
  },
}
</script>
<style scoped lang="scss"></style>
